import { loginApi, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    user: null, //自己设置一个用户信息
  }
}

const state = getDefaultState()


// mutations只能改变仓库【使用 commit】
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER: (state, payload) => {
    state.user = payload
  }

}

// 通过 执行mutation改变仓库【使用 dispatch】
const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginApi(userInfo).then(ret => {
        const { data } = ret; //解构
        if (data) {
          //有数据
          // console.log(data, ":::data")
          commit('SET_USER', data)
          resolve()
        } else {
          //没有数据
          reject(ret)
        }
      }).catch(error => {
        reject(error)
      })
    })

    // const {username, password} = userInfo
    // return new Promise((resolve, reject) => {
    //   login({username: username.trim(), password: password}).then(response => {
    //     const {data} = response
    //     commit('SET_TOKEN', data.token)
    //     setToken(data.token)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // get user info 【恢复登录】
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 发送请求
      getInfo().then(result => {
        // console.log(result, '<<<<result')
        if (typeof result === 'string') {
          //   失败【string 未登录，登录过期】
          result = JSON.parse(result)
          if (result.code === 401) {
            reject(result.msg)
          }
        } else {
          // 成功就把信息放到仓库
          commit('SET_USER', result.data)
          resolve()
        }
      })

      // getInfo(state.token).then(response => {
      //   const {data} = response
      //   if (!data) {
      //     return reject('Verification failed, please Login again.')
      //   }
      //   const {name, avatar} = data
      //   commit('SET_NAME', name)
      //   commit('SET_AVATAR', avatar)
      //   resolve(data)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  }
  ,

  // user logout【退出登录】
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first【删除token】
      resetRouter()
      commit('RESET_STATE')
      resolve()

      // logout(state.token).then(() => {
      //   removeToken() // must remove  token  first【删除token】
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

